//
//  UserCount.swift
//  WSWB
//
//  Created by 刘 伟生 on 16/1/12.
//  Copyright © 2016年 seasa. All rights reserved.
//

import UIKit

class UserCount: NSObject, NSCoding {
    //MARK:- 属性
    var access_token : String?
    var expires_in : Int = 0 {
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: Double(expires_in))
        }
    }
    var remind_in : Int = 0
    var uid : String?
    var expires_Date : NSDate?
    //用户图片
    var avatar_large : String?
    //用户昵称
    var screen_name : String?
    
    
    //创建一个类方法来字典转模型
    init(dict : [String : AnyObject]) {
        super.init()
        // 字典转模型
        // 如果现在构造方法中使用KVC必须先对当前对象进行初始化
        setValuesForKeysWithDictionary(dict)
        // 注意: 如果在构造方法中使用KVC赋值, 基本数据类型的属性必须有初始化值
        
    }
    
    override var description :String {
        let keys = ["access_token","expires_in" ,"uid"];
        
        let dict = dictionaryWithValuesForKeys(keys)
        return "\(dict)"
    }
    
    //设置保存路径
    static let pathStr = "userAccount.plist".cachesDir()
    static var userCount : UserCount?
    
    //将对象保存到文件中去
    func saveUserCount() -> Bool {
        
        return NSKeyedArchiver.archiveRootObject(self, toFile: UserCount.pathStr)
    }
    
    //将对象从文件中获取
    class func loadUserCountFromFile() ->UserCount?{
        
        
        //首先要判断是否有加载过,如果加载过,那么久保存在当前对象的属性值中(内存),不用每次都从文件中获取
        if UserCount.userCount != nil{
            return UserCount.userCount!
        }
        
        //从文件中解档获取对象
        let userCount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserCount.pathStr) as? UserCount
        
        //判断是否过期
           if let date = UserCount.userCount?.expires_Date where  NSDate().compare(date) == NSComparisonResult.OrderedDescending
           {
            //此时说明文件过期
            UserCount.userCount = nil
            return nil
        }
        //保存
        
        UserCount.userCount = userCount

        return UserCount.userCount
    }
    
    //加载用户信息
    func loadUserInfo(finish: (dict : [String : AnyObject]?, error : String?) -> ()){
                      
        //发送请求,获取用户数据
        //1.1首先要拼接参数,准备路径
        let path = "2/users/show.json"
        
        //断言:就是说明某个值的一定是什么,如果不是,那么就会报错;从而实现方便程序员之间交流
        assert(access_token != nil, "access_token的值一定不能为空")
        assert(uid != nil, "uid的值一定不是空")
        
        let pragma = ["access_token" : access_token! ,"uid" : uid!]
        
        //1.2发送请求
        NetWorkTool.shareInstance.GET(path, parameters: pragma, success: { (task, objc) -> Void in
            
            //对数据进行校验(但凡是从网络上下载来的的数据和通知传递过来的数据都需要进行校验)
            guard let dict = objc as? [String: AnyObject] else {
                print("获取数据失败")
                return
            }
            
            self.saveUserCount()
            
            //保存用户昵称和用户图片
            self.screen_name = dict["screen_name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            print("----->\(dict)")
            
            }) { (task, error) -> Void in
                //下载数据失败,同样需要授权时候的数据
                print("获取用户数据失败")
                self.saveUserCount()
        }
        
    }
    
   
    //实现NSCoding的协议方法,用于归档和解档
    func encodeWithCoder(aCoder: NSCoder) {//归档
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(remind_in, forKey: "remind_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {//解档
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as! Int
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        
    
    }
    
    //判断是否已经登录
    class  func islogin() -> Bool {
        print(UserCount.pathStr)
        return UserCount.loadUserCountFromFile() != nil
    }

}
